package com.b2s.scrumblr.kb.core.redis;

import com.b2s.scrumblr.kb.core.util.CommonsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2016/9/1.
 */
@Component
public class RedisOperations {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate template ;

    public boolean exists(String key){
        return template.hasKey(key);
    }

    public void remove(String key){
        if(exists(key)){
            template.delete(key);
        }
    }

    public void remove(String... keys){
        for(String key: keys){
            remove(key);
        }
    }

    public void removePattern(String pattern){
        Set keys = template.keys(pattern);
        if(CommonsUtil.isNotEmpty(keys)){
            template.delete(keys);
        }
    }

    public Object get(String key){
        ValueOperations<Serializable, Object> operations = template.opsForValue();
        return operations.get(key);
    }

    public void set(String key, Object obj, long expireTime){
        ValueOperations<Serializable, Object> operations = template.opsForValue();
        operations.set(key, obj);
        template.expire(key, expireTime, TimeUnit.HOURS);
    }
}
